/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.ndk.head;

import android.graphics.Bitmap;
import android.util.Log;

import com.ndk.head.uvc.bean.ImageBean;
import com.ndk.head.uvc.utils.BitmapUtil;

import java.util.List;

/**
 * create by itz on 2024-11-25 10:27
 * desc :
 **/
public class ImageCheck {
    static {
        System.loadLibrary("native-lib");
    }

    private long mNativeObj = 0;

    public ImageCheck() {
        mNativeObj = nativeCreateImageCheck();
    }

    public void detectImageCheck(String path) {
        Log.e("ImageCheck", "detectImageCheck path = " + path);
        Bitmap bitmap = BitmapUtil.getBitmapFromPath(path);
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            byte[] imageBytes = BitmapUtil.convertBitmapToByteArray(bitmap);
            Log.e("ImageCheck", "detectImageCheck width = " + width + ",height = " + height + ",imageBytes = " + imageBytes.length);

            // 现在您可以使用 imageBytes 进行进一步处理，比如上传到服务器或保存到本地文件等
            //String result = detect(imageBytes, width, height);
            String result = detect(bitmap);
            Log.e("ImageCheck", "detectImageCheck result = " + result);
            List<ImageBean> imageBeans = ImageBean.parseJSON(result);
            // 绘制图片，给 Bitmap 添加红色框
            Bitmap bitmapWithBox = bitmap;
            for (int i = 0; i < imageBeans.size(); i++) {
                ImageBean imageBean = imageBeans.get(i);
                bitmapWithBox = BitmapUtil.drawRedBoxOnBitmap(bitmapWithBox, imageBean.getX1(), imageBean.getY1(), imageBean.getX2(), imageBean.getY2());
            }
            String newPath = path.split(".jpg")[0] + "_new.jpg";
            BitmapUtil.saveBitmap(bitmapWithBox, newPath);
        } else {
            Log.e("ImageCheck", "detectImageCheck 无法加载图片");
        }
    }

    public String detect(byte[] inputImage, int width, int height) {
        return nativeDetectImageCheck(mNativeObj, inputImage, width, height);
    }

    public String detect(Bitmap bitmap) {
        return processBitmap(bitmap);
    }

    // 从 Bitmap 获取像素数据并调用 native 方法
    public String processBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int[] pixels = new int[width * height];

        // 获取 Bitmap 的像素数据
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        Log.e("ImageCheck", "pixels.length = " + pixels.length);
        // 调用 JNI 方法将像素数据转换为 Mat
        return  nativeDetectBitmap(mNativeObj, pixels, width, height);
    }

    /**
     * Native层函数
     */
    private static native long nativeCreateImageCheck();

    private static native String nativeDetectImageCheck(long thiz, byte[] inputImage, int width, int height);

    private static native String nativeDetectBitmap(long thiz, int[] pixels, int width, int height);
}
